package cn.funeralobjects.util;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * CSV文件工具
 *
 * @author FuneralObjects
 * Create date: 2020/4/3 3:45 PM
 */
public class CsvUtils {

    public static final String CSV_DELIMITER = ",";
    private static final String NEW_LINE = System.lineSeparator();

    /**
     * 将多行记录，写入到文件后面
     *
     * @param data 多行记录
     * @param file 被写入文件
     */
    public static void appendToFileForList(List<List<String>> data, File file) {
        assert file != null;
        try {
            write(data.parallelStream()
                    .filter(row -> !CollectionUtils.isEmpty(row))
                    .map(row -> CollectionUtils.join(row, CSV_DELIMITER))
                    .collect(Collectors.toList()), new BufferedWriter(new FileWriter(file, true)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将多行记录，写入到文件后面
     *
     * @param data 多行记录
     * @param file 被写入文件
     */
    public static void appendToFileForArray(List<String[]> data, File file) {
        assert file != null;
        try {
            write(data.parallelStream()
                    .filter(row -> row.length != 0)
                    .map(row -> String.join(CSV_DELIMITER, row))
                    .collect(Collectors.toList()), new BufferedWriter(new FileWriter(file, true)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 直接重写文件
     *
     * @param data 多行记录
     * @param file 被写入文件
     */
    public static void rewriteToFileForArray(List<String[]> data, File file) {
        assert file != null;
        try {
            write(data.parallelStream()
                    .filter(row -> row.length != 0)
                    .map(row -> String.join(CSV_DELIMITER, row))
                    .collect(Collectors.toList()), new BufferedWriter(new FileWriter(file)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<String[]> readFile(File file) {
        if (!file.exists()) {
            return Collections.emptyList();
        }
        try {
            return read(new FileInputStream(file)).parallelStream().map(row -> row.split(CSV_DELIMITER)).collect(Collectors.toList());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private static List<String> read(InputStream inputStream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        List<String> data = new ArrayList<>();
        String temp;
        try {
            while ((temp = reader.readLine()) != null) {
                data.add(temp);
            }
            return data;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void write(List<String> data, Writer writer) {
        if (CollectionUtils.isEmpty(data)) {
            return;
        }
        try {
            for (String row : data) {
                writer.write(row);
                writer.write(NEW_LINE);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
